package gang.com.twoshopping.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import gang.com.twoshopping.R;
import gang.com.twoshopping.adapter.HomeCatgoryAdapter;
import gang.com.twoshopping.bean.Banner;
import gang.com.twoshopping.bean.Campaign;
import gang.com.twoshopping.bean.HomeCampaign;
import gang.com.twoshopping.bean.HomeCategory;
import gang.com.twoshopping.http.BaseCallBack;
import gang.com.twoshopping.http.OkHttpHelper;
import gang.com.twoshopping.http.SpotsCallBack;
import gang.com.twoshopping.utils.Contants;
import gang.com.twoshopping.weight.DividerItemDecoration;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xiaogangzai on 2017/5/7.
 */

public class HomeFragment extends Fragment {
    private SliderLayout msliderShow;
    private PagerIndicator mIndicator;
    private RecyclerView mRecyclerView;
    private HomeCatgoryAdapter mAdapter;
    private List<HomeCategory> dates = new ArrayList<>();
    private Gson mGson = new Gson();
    private List<Banner> bannerList;
    private OkHttpHelper okHttpHelper;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        msliderShow = (SliderLayout) view.findViewById(R.id.slider);
        mIndicator = (PagerIndicator) view.findViewById(R.id.custom_indicator);
        requestImages();
        // initSliderview();
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        inistDates();
        initRecyclerViewDate();
        return view;
    }


    private void initRecyclerViewDate() {
        okHttpHelper.get(Contants.ApI.CAMPIGH_HOME, new BaseCallBack<List<HomeCampaign>>() {


            @Override
            public void onRequestBefore(Request request) {

            }

            @Override
            public void onFailure(IOException e) {

            }

            @Override
            public void onSucess(Response response, List<HomeCampaign> homeCategories) {
                showRecyleview(homeCategories);
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onResponse(Response response) {

            }
        });


    }

    private void showRecyleview(final List<HomeCampaign> homeCategories) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter = new HomeCatgoryAdapter(homeCategories, getActivity());
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                mRecyclerView.setAdapter(mAdapter);
                mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
                mAdapter.setOnItemClickListener(new HomeCatgoryAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(View v, Campaign campaign) {
                        Toast.makeText(getActivity(), campaign.getTitle(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        });

    }

    private void inistDates() {
        HomeCategory category = new HomeCategory("热门活动", R.drawable.default_head, R.drawable.default_head, R.drawable.default_head);
        dates.add(category);
        category = new HomeCategory("有利可图", R.drawable.default_head, R.drawable.default_head, R.drawable.default_head);
        dates.add(category);
        category = new HomeCategory("品牌街", R.drawable.default_head, R.drawable.default_head, R.drawable.default_head);
        dates.add(category);
        category = new HomeCategory("经典城", R.drawable.default_head, R.drawable.default_head, R.drawable.default_head);
        dates.add(category);

    }

    private void initSliderview() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (bannerList != null) {
                    for (Banner banner : bannerList) {
                        TextSliderView textSliderView = new TextSliderView(getActivity());
                        textSliderView
                                .description(banner.getName())
                                .image(banner.getImgUrl());
                        msliderShow.addSlider(textSliderView);
                    }
                }
        /*TextSliderView textSliderView = new TextSliderView(this.getActivity());
        textSliderView
                .description("Game of Thrones")
                .image("http://pic.58pic.com/58pic/14/27/45/71r58PICmDM_1024.jpg");
        //TextSliderView的监听事件
        textSliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
            @Override
            public void onSliderClick(BaseSliderView slider) {
                Toast.makeText(getActivity(), "啦啦啦第一个", Toast.LENGTH_LONG);
            }
        });*/

                //这是系统自带的indicator
                //msliderShow.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
                msliderShow.setPresetTransformer(SliderLayout.Transformer.RotateUp);
                msliderShow.setDuration(3000);
                //使用自定义的indicator
                msliderShow.setCustomIndicator(mIndicator);
                msliderShow.setCustomAnimation(new DescriptionAnimation());
                //添加监听事件
                msliderShow.addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        });

    }

    private void requestImages() {
        String url = "http://112.124.22.238:8081/course_api/banner/query?type=1";
        okHttpHelper = OkHttpHelper.getInstance();
        okHttpHelper.get(url, new SpotsCallBack<List<Banner>>(getActivity()) {

            @Override
            public void onSucess(Response response, List<Banner> banners) {
                bannerList = banners;
                initSliderview();
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
        /*OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        //异步方法
        okHttpClient.newCall(request).enqueue(new Callback() {
            //收件人快递的例子
            //请求网络时出现不可恢复的错误时调用该方法，例如网络地址错了，服务器死了
            @Override
            public void onFailure(Call call, IOException e) {
            }

            //请求成功时调用该方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //状态码大于200小于300
                if (response.isSuccessful()) {
                    //do sucess
                    String json = response.body().string();
                    Log.i("HomeFragment", "json=" + json);
                    Type type = new TypeToken<List<Banner>>() {
                    }.getType();
                    bannerList = mGson.fromJson(json, type);
                    initSliderview();
                } else {
                    //do error
                }
            }
        });*/
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        msliderShow.startAutoCycle();
    }
}
